<template>
  <basic-container>
    <div class="avue-crud">
      <!-- 搜索工作栏 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="组名" prop="groupName">
          <el-input v-model="queryParams.groupName" placeholder="请输入组名" clearable
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option v-for="dict in this.getDictDataByType(DICT_TYPE.COMMON_STATUS)"
                       :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="dateRangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd"
                          type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作工具栏 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                     v-if="permissions.bpm_user_group_add">新增
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 列表 -->
      <el-table v-loading="loading" :data="list">
        <el-table-column label="编号" align="center" prop="id"/>
        <el-table-column label="组名" align="center" prop="groupName"/>
        <el-table-column label="描述" align="center" prop="description"/>
        <el-table-column label="成员" align="center">
          <template slot-scope="scope">
            <el-tag size="medium" v-if="scope.row.userIds" :key="userId" v-for="userId in scope.row.userIds">
              {{ getUserName(userId) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                       v-if="permissions.bpm_user_group_edit">修改
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-if="permissions.bpm_user_group_del">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size"
                  @pagination="getList"/>

      <!-- 对话框(添加 / 修改) -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="组名" prop="groupName">
            <el-input v-model="form.groupName" placeholder="请输入组名"/>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入描述"/>
          </el-form-item>
          <el-form-item label="成员" prop="userIds">
            <el-select v-model="form.userIds" multiple placeholder="请选择成员">
              <el-option v-for="user in users" :key="user.id" :label="user.userName"
                         :value="user.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio v-for="dict in this.getDictDataByType(DICT_TYPE.COMMON_STATUS)"
                        :key="dict.value" :label="dict.value">{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </basic-container>

</template>

<script>
import {addObj, putObj, delObj, getObj, fetchList} from "@/api/bpm/user-group";
import {CommonStatusEnum} from "@/util/bpm/constants";
import {listUser} from "@/api/admin/auth/user";
import {mapGetters} from "vuex";

export default {
  name: "UserGroup",
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户组列表
      list: [],
      // 用户列表
      users: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        groupName: null,
        status: null,
        tenantId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        groupName: [{required: true, message: "组名不能为空", trigger: "blur"}],
        description: [{required: true, message: "描述不能为空", trigger: "blur"}],
        userIds: [{required: true, message: "成员不能为空", trigger: "change"}],
        status: [{required: true, message: "状态不能为空", trigger: "blur"}],
      }
    };
  },
  computed: {
    ...mapGetters(["permissions"])
  },
  created() {
    this.getList();
    // 获得用户列表
    listUser().then(response => {
      this.users = response.data.data;
    })
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行查询
      fetchList(params).then(response => {
        this.list = response.data.data.records;
        this.total = response.data.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        groupName: undefined,
        description: undefined,
        userIds: [],
        status: CommonStatusEnum.ENABLE,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户组";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getObj(id).then(response => {
        this.form = response.data.data;
        this.open = true;
        this.title = "修改用户组";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          putObj(this.form).then(response => {
            this.$message.success("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        addObj(this.form).then(response => {
          this.$message.success("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$confirm('是否确认删除用户组编号为"' + id + '"的数据项?').then(function () {
        return delObj(id);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {
      });
    },
    getUserName(userId) {
      for (const user of this.users) {
        if (user.id === userId) {
          return user.userName;
        }
      }
      return '未知(' + userId + ')';
    },
  }
};
</script>
